package com.xvyy.tingshu.order.adapter.impl;

import com.xvyy.tingshu.album.client.AlbumInfoFeignClient;
import com.xvyy.tingshu.common.constant.SystemConstant;
import com.xvyy.tingshu.common.result.Result;
import com.xvyy.tingshu.model.album.AlbumInfo;
import com.xvyy.tingshu.model.album.TrackInfo;
import com.xvyy.tingshu.order.adapter.OrderDealTypeAdapter;
import com.xvyy.tingshu.order.mapper.OrderInfoMapper;
import com.xvyy.tingshu.vo.order.OrderDetailVo;
import com.xvyy.tingshu.vo.order.OrderInfoVo;
import com.xvyy.tingshu.vo.order.TradeVo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName: OrderDealTypeByTrack
 * Package: com.xvyy.tingshu.order.adapter.impl
 *
 * @Description:
 * @Author: xvyy
 * @Create: 2025/2/16 - 0:16
 * @Version: v1.0
 */
@Component
@Slf4j
public class OrderDealTypeByTrack implements OrderDealTypeAdapter {

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Override
    public Boolean supportOrderDealType(String dealType) {
        return SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(dealType);
    }

    @Override
    public OrderInfoVo adapterOrderDealType(TradeVo tradeVo, Long userId, String itemType)  {
        OrderInfoVo orderInfoVoResult = new OrderInfoVo();
        Long trackId = tradeVo.getItemId();
        // 1. 幂等性判断 判断是否买过该声音
        Integer trackCount = tradeVo.getTrackCount();
        Result<TrackInfo> trackInfoResult = albumInfoFeignClient.getTrackInfoById(trackId);
        TrackInfo trackInfoData = trackInfoResult.getData();
        Assert.notNull(trackInfoData, "远程调用album微服务，获取声音信息失败");
        Long albumId = trackInfoData.getAlbumId();
        Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
        AlbumInfo albumInfoData = albumInfoResult.getData();
        Assert.notNull(albumInfoData, "远程调用album微服务，获取专辑信息失败");
        // 2. 幂等性校验综合方法，判断是否在支付中，查询声音并过滤购买过的声音
        Result<List> canPayTrackList = albumInfoFeignClient.getPaidTrackAndFilterCanPayTrack(albumId, userId, trackCount, trackId);
        Integer code = canPayTrackList.getCode();
        // 2.1 判断是否买过该声音
        if (code == 400) {
            // 返回买过的声音
            List<Object> data = canPayTrackList.getData();
            orderInfoVoResult.setExitItemIdList(data);
            return orderInfoVoResult;
        }
        // 2.2 判断能买的声音列表
        List<Map> canPayTrackListData = canPayTrackList.getData();
        Assert.notNull(canPayTrackListData, "远程调用album微服务，声音列表失败");
        // 2.3 买过的声音查询出来又能把买过的声音过滤掉
        List<Long> paidTrackIdList = orderInfoMapper.checkTrackTypeItemPadding(itemType, userId);
        List<Map> paddingTrackMapList = canPayTrackListData.stream().filter(map -> paidTrackIdList.contains(map.get("id"))).collect(Collectors.toList());
        List<Object> exitItemIdList = new ArrayList<>();
        // 2.4 判断是否在支付中
        if (!CollectionUtils.isEmpty(paddingTrackMapList)) {
            // 2.4.1 在支付中
            for (Map map : paddingTrackMapList) {
                exitItemIdList.add(map.get("id"));
                log.error("该付款项声音：{}，处于购买中，请勿继续购买该声音", map.get("id"));
            }
            // 返回给前端
            orderInfoVoResult.setExitItemIdList(exitItemIdList);
            return orderInfoVoResult;
        }
        // 2.4.2 不在支付中，可以继续购买
        // 3. 给OrderInfoVo赋值
        // 3.1 订单号
        String tradeNo = RandomStringUtils.random(12, true, true);
        orderInfoVoResult.setTradeNo(tradeNo);
        // 3.2 支付方式
        orderInfoVoResult.setPayWay("");
        // 3.3 交易类型
        orderInfoVoResult.setItemType(itemType);
        // 3.4 原始金额
        BigDecimal trackPrice = albumInfoData.getPrice();
        BigDecimal originalAmount = trackCount == 0 ? trackPrice : trackPrice.multiply(new BigDecimal(trackCount));
        orderInfoVoResult.setOriginalAmount(originalAmount.setScale(2, RoundingMode.HALF_UP));
        // 3.5 减免金额
        orderInfoVoResult.setDerateAmount(new BigDecimal("0.00").setScale(2, RoundingMode.HALF_UP));
        // 3.6 实付金额
        orderInfoVoResult.setOrderAmount(originalAmount.setScale(2, RoundingMode.HALF_UP));
        // 3.7 订单详情列表
        ArrayList<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        for (Map map : canPayTrackListData) {
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            Object id = map.get("id");
            orderDetailVo.setItemId(Long.parseLong(id + ""));
            orderDetailVo.setItemName((String) map.get("trackTitle"));
            orderDetailVo.setItemUrl((String) map.get("coverUrl"));
            orderDetailVo.setItemPrice(trackPrice.setScale(2, RoundingMode.HALF_UP));
            orderDetailVoList.add(orderDetailVo);
        }
        orderInfoVoResult.setOrderDetailVoList(Lists.newArrayList(orderDetailVoList));
        // 3.8 订单减免列表
        orderInfoVoResult.setOrderDerateVoList(Lists.newArrayList());//声音不打折
        // 4. 返回结果
        return orderInfoVoResult;
    }
}
